package com.example.reggie.common.exception;

import com.example.reggie.common.table.MsgTable;
import com.example.reggie.common.deploy.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

@ControllerAdvice(annotations = {RestController.class,Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception){
        if(exception.getMessage().contains("Duplicate entry")){
            String[] ex_s = exception.getMessage().split(" ");
            String msg=ex_s[2];
            return R.error(MsgTable.DUPLICATED_ERROR+":"+msg);
        }
        return R.error(MsgTable.UNKNOWN_ERROR);
    }

    @ExceptionHandler(ServiceException.class)
    public R<String> serviceExceptionHandler(ServiceException exception){
        log.error(exception.getMessage());
        return R.error(exception.getMessage());
    }
}
